import { useState, useEffect, useRef, useMemo } from 'react';
import { Table, Form, MF } from 'com';
import menuStore from 'store/menu';
import { Space, Button } from 'antd';
import { Search, Add, Update, Delete } from 'api/course_list';
import { getSubjects } from 'api/dictionary';
import { asyncConfirm } from '@/utils/common';
import dayjs from 'dayjs';

export default () => {
    /**
        * 列表
        */
    const [list, setList] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 课程
     */
    const [course, setCourse] = useState({});
    /**
     * 总条数
     */
    const [total, setTotal] = useState(0);
    /**
     * 科目列表
     */
    const [subjects, setSubjects] = useState([{ label: '所有', value: 0 }]);
    /**
     * 列
     */
    const cols = [
        {
            title: '班级',
            dataIndex: 'class_name',
            align: 'center'
        },
        {
            title: '科目',
            dataIndex: 'subject_name',
            align: 'center'
        },
        {
            title: '教师',
            dataIndex: 'teacher_name',
            align: 'center'
        },
        {
            title: '开始时间',
            dataIndex: 'from_date',
            align: 'center',
            render: text => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '结束时间',
            dataIndex: 'end_date',
            align: 'center',
            render: text => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '状态',
            dataIndex: 'status',
            align: 'center'
        },
        {
            title: '操作',
            align: 'center',
            width: 150,
            render: (text, row) => <Space>
                {menuStore.auth('updateCourse') && <Button type="link" size="small" onClick={() => {
                    setCourse({
                        ...row,
                        class_id: { id: row.class_id, name: row.class_name },
                        teacher_id: { id: row.teacher_id, name: row.teacher_name },
                        from_date: [dayjs(row.from_date), dayjs(row.end_date)]
                    });
                    addMF.current.show();
                }}>修改</Button>}
                {menuStore.auth('deleteCourse') && <Button type="link" size="small" onClick={() => deleteCourse(row)}>删除</Button>}
            </Space>
        }
    ]
    /**
     * 添加MF引用
     */
    const addMF = useRef();
    /**
     * 添加修改表单配置项
     */
    const addUpdateOptions = useMemo(() => {
        const [a, ...rest] = subjects;
        return {
            class_id: {
                title: '班级',
                tag: 'cs',
                required: true
            },
            teacher_id: {
                title: '教师',
                tag: 'ts',
                required: true,
            },
            subject_id: {
                title: '科目',
                tag: 'select',
                required: true,
                values: rest
            },
            from_date: {
                title: '课程时间',
                tag: 'dateRange',
                showTime: true,
                required: true,
            }
        }
    }, [subjects]);
    /**
     * 搜索表单配置项
     */
    const options = useMemo(() => ({
        ...(menuStore.auth('course') && {
            class_id: {
                title: '班级',
                tag: 'cs',
                clear: true
            },
            teacher_id: {
                title: '教师',
                tag: 'ts',
                clear: true
            },
            subject_id: {
                title: '科目',
                tag: 'select',
                values: subjects
            },
            from_date: {
                title: '开始时间',
                tag: 'date',
                style: { width: 190 },
                attrs: { showTime: true }
            },
            end_date: {
                tag: 'date',
                style: { width: 190 },
                attrs: { showTime: true }
            },
            search: {
                tag: 'button',
                text: '搜索',
                htmlType: 'submit',
                type: 'primary'
            }
        }),
        ...(menuStore.auth('addCourse') && {
            add: {
                tag: 'button',
                text: '添加',
                type: 'primary',
                click: () => {
                    setCourse({});
                    addMF.current.show();
                }
            }
        })
    }), [subjects]);

    /**
     * 搜索模型
     */
    const [searchModel, setSearchModel] = useState({
        pageNo: 1,
        pageSize: 10,
        subject_id: 0
    });

    menuStore.auth('course') && useEffect(() => {
        (async () => {
            setLoading(true);
            try {
                const { from_date, end_date, ...rest } = searchModel;
                const { data, total } = await Search({ ...rest, from_date: from_date && dayjs(from_date).format('YYYY-MM-DD HH:mm:ss'), end_date: end_date && dayjs(end_date).format('YYYY-MM-DD HH:mm:ss') });
                setList(data);
                setTotal(total);
            } catch (error) { }
            setLoading(false);
        })()
    }, [searchModel]);

    menuStore.auth('course') && useEffect(() => {
        (async () => {
            try {
                const list = await getSubjects();
                setSubjects([...subjects, ...list.map(c => ({ label: c.name, value: c.id }))]);
            } catch (error) { }
        })()
    }, []);

    /**
     * 提交
     * @param {*} values 
     */
    const confirm = async values => {
        try {
            const { from_date: [start, end] } = values;
            addMF.current.start();
            await (course.id ? Update : Add)({ ...values, id: course.id, from_date: start.format('YYYY-MM-DD HH:mm:ss'), end_date: end.format('YYYY-MM-DD HH:mm:ss') });
            addMF.current.hide();
            setSearchModel({ ...searchModel });
        } catch (error) {
            console.log(error);
        }
        addMF.current.stop();
    }

    /**
     * 删除课程
     * @param {*} row 
     */
    const deleteCourse = async ({ id, class_name, from_date, end_date }) => {
        let res;
        try {
            res = await asyncConfirm(`您确定要删除${class_name}班${dayjs(from_date).format('YYYY-MM-DD HH:mm:ss')}至${dayjs(end_date).format('YYYY-MM-DD HH:mm:ss')}的课程吗？`);
            await Delete(id);
            setSearchModel({ ...searchModel });
        } catch (error) { }
        res && res.close();
    }

    return <div>
        <h3>课表管理</h3>
        <hr />
        {menuStore.auth('course', 'addCourse') && <Form options={options} values={searchModel} attrs={{ layout: "inline" }} onFinish={v => setSearchModel({ ...searchModel, ...v, pageNo: 1 })} />}
        <p></p>
        {menuStore.auth('course') && <Table cols={cols} data={list} loading={loading} total={total} page={searchModel} onChange={setSearchModel} />}
        {menuStore.auth('addCourse') && <MF onFinish={confirm} options={addUpdateOptions} title={course.id ? '修改课程' : '添加课程'} ref={addMF} lw={80} values={course} />}
    </div>
}